package cn.edu.anan.datastructure.line;

/**
 * 循环队列
 */
public class CircularQueue<E> {

    private Object[] items;
    private int n;

    // 队头、对尾指针
    private int head;
    private int tail;

    public CircularQueue(int capacity){
        items = new Object[capacity];
        n = capacity;
    }

    /**
     * 入队操作
     */
    public boolean enqueue(E e){
        // 判断队列是否满
        // 队列满条件：(tail + 1) % n == head
        if((tail + 1) % n == head){
            return false;
        }

        items[tail] = e;
        tail = (tail + 1) % n;

        return true;
    }

    /**
     * 出队操作
     */
    public E dequeue(){
        // 判断队列是否空
        // 队列空条件：tail == head
        if(tail == head){
            return null;
        }

        E e = (E)items[head];
        head = (head + 1) % n;

        return e;
    }
}
